import { createRouter, createWebHashHistory } from "vue-router";
import { useLoginStore } from '@/store/app.js'

export const Layout = () => import("@/components/Layout");

const routes = [
  {
    path: "/",
    name: "/",
    component: Layout,
    redirect: "/work",
    children: [
      {
        path: "work",
        name: "work",
        component: () => import("@/views/NurseWork.vue")
      },
      {
        path: "/rtms",
        component: () => import("@/views/PatRtmsView.vue"),
        name: "rtms",
      },
      {
        path: "/user",
        component: () => import("@/views/UsersView.vue"),
        name: "user",
      },
      {
        path: "/print",
        component: () => import("@/views/PrintTempView.vue"),
        name: "print",
      }
    ]
  },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
    name: "login",
  },{
    path: "/design",
    component: () => import("@/components/PrintDesign/index.vue"),
    name: "design"
  },
  {
    path: "/viewer",
    component: () => import("@/components/PrintViewer/index.vue"),
    name: "viewer",
  }
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

const whiteList = ['/login'];
router.beforeEach((to, from, next) => {

const loginStore = useLoginStore();

  if (loginStore.getToken) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path))
      next();
    else
      next('/login' + '?redirect=' + to.path)
  }
})

export default router;
